package com.wang.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wang.entity.User;
import com.wang.utils.ConstantUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname ApiLoginInterceptor
 * @Description TODO
 * @Date 2024/10/14 8:58
 * @Created by pc
 */
@Component
public class ApiLoginInterceptor implements HandlerInterceptor {
    // 请求之前执行
    // 如果是登录状态 就放行 否则就不能放行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        User loginUser = (User) session.getAttribute(ConstantUtil.LOGIN_USER);
        if(loginUser == null){
            // 没有登录
            ObjectMapper om = new ObjectMapper();
            Map<Object,Object> map = new HashMap<>();
            map.put("code",400);
            map.put("msg","用户没有登录,不能访问后续接口");
            String json = om.writeValueAsString(map);
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(json);
            writer.flush();
            writer.close();
            return false;
        }else{
            return true;
        }
    }
}
